package com.quanfaqiang.demo1.aop;


import com.alibaba.fastjson.JSONObject;
import com.quanfaqiang.demo1.mapper.OperateLogMapper;
import com.quanfaqiang.demo1.pojo.OperateLog;
import com.quanfaqiang.demo1.pojo.User;
import com.quanfaqiang.demo1.service.UserService;
import com.quanfaqiang.demo1.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private UserService userService;
    @Around("@annotation(com.quanfaqiang.demo1.anno.Log))")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println(map);
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        LocalDateTime now = LocalDateTime.now();//操作时间
        String className = joinPoint.getTarget().getClass().getName();//操作类名
        String methodName = joinPoint.getSignature().getName();//操作方法名
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);//操作方法参数
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();//调用原始目标方法运行
        long end = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);//方法返回值
        String string = result.toString();
        System.out.println(string+"******************");
        String operateName="";

        Long costTime=end-begin;
        OperateLog operateLog = new OperateLog(null,username,now,"修改",operateName,methodParams,returnValue);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日记：{}",operateLog);
        return result;

    }
}
